package com.livesource.client.webservices;

import java.util.Date;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.livesource.client.LiveSourceGlobalVariables;
import com.livesource.client.model.entry.ProjectClass;

/**
 * Communicates via REST Web Service
 */
public class RequestSaveLiveFeed {

	// http://localhost:8888/PutService?kind=LiveFeed
	// &fieldsKind=Entity&fieldsName=entityIDTo&fieldsValue=AllineO
	// &fieldsKind=Entity&fieldsName=entityIDFrom&fieldsValue=LiveSource
	// &fieldsKind=String&fieldsName=liveFeedDescription&fieldsValue=@AllineO
	// now connected to @LiveSource
	// &fieldsKind=Date&fieldsName=liveFeedDate&fieldsValue=170000000

	private static String url = "http://jsonpfy.projectnection.appspot.com/PutService";

	public static void sendPostRequest(String liveFeedDescription) {

		String urlSave = url
				+ "?kind=LiveFeed"
				+ "&fieldsKind=Entity&fieldsName=entityIDTo&fieldsValue="
				+ LiveSourceGlobalVariables.currentProject.getProjectID()
				+ "&fieldsKind=Entity&fieldsName=entityIDFrom&fieldsValue="
				+ LiveSourceGlobalVariables.userID
				+ "&fieldsKind=String&fieldsName=liveFeedDescription&fieldsValue="
				+ liveFeedDescription
				+ "&fieldsKind=Date&fieldsName=liveFeedDate&fieldsValue="
				+ new Date().getTime();

		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
				urlSave);

		// builder.setRequestData(requestData);

		try {
			Request request = builder.sendRequest(null, new RequestCallback() {

				public void onError(Request request, Throwable exception) {
					// displayError("Couldn't retrieve JSON");
				}

				public void onResponseReceived(Request request,
						Response response) {
					if (200 == response.getStatusCode()) {
						// updateTable(asArrayOfStockData(response.getText()));
					} else {
						// displayError("Couldn't retrieve JSON ("
						// + response.getStatusText() + ")");
					}
				}
			});
		} catch (RequestException e) {
			// displayError("Couldn't retrieve JSON");
		}

	}

	public static void feedUpdateTask(String userID, ProjectClass task) {

		String liveFeedDescription = "@" + userID + " updated the task @"
				+ task.getClassName();

		sendPostRequest(liveFeedDescription);
	}

	public static void feedUpdateFeature(String userID, ProjectClass feature) {

		String liveFeedDescription = "@" + userID + " updated the feature @"
				+ feature.getClassName();

		sendPostRequest(liveFeedDescription);
	}
}
